<template>
  <div style="padding: 10px;">
    <!-- header  -->
    <div class="header">
      <el-row>
        <el-col :span="18">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <el-input v-model="searchParams.courseName" placeholder="请输入课程名称" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="searchParams.courseType" placeholder="课程类型" clearable>
                <el-option
                  v-for="item in courseTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6" style="text-align: right;">
          <el-button type="primary" @click="handleAddCourse">添加课程</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- table -->
    <div class="table">
      <el-table :data="courseData" style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="50" align="center">
        </el-table-column>
        <el-table-column prop="courseName" label="课程名称" width="300" align="center">
        </el-table-column>
        <el-table-column prop="courseType" label="课程类型" align="center">
          <template v-slot="scope">
            {{ formatCourseType(scope.row.courseType) }}
          </template>
        </el-table-column>
        <el-table-column prop="teacherName" label="授课教师" align="center">
        </el-table-column>
        <el-table-column prop="studentCount" label="学生人数" width="100" align="center">
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" align="center">
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status === 1" type="success">已开课</el-tag>
            <el-tag v-else-if="scope.row.status === 0" type="warning">未开课</el-tag>
            <el-tag v-else type="danger">已结课</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-link style="margin-left: 5px;font-size: 12px;" :underline="false" type="warning" @click="editCourse(scope.row)">编辑</el-link>
            <el-link style="margin-left: 5px;font-size: 12px;" :underline="false" type="danger" @click="deleteCourse(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- pagination -->
    <div class="page" style="margin-top:10px;">
      <el-pagination 
        hide-on-single-page 
        background 
        @current-change="handleCurrentChange" 
        :current-page="pagination.page" 
        :page-size="pagination.pageSize"
        layout="prev, pager, next, jumper" 
        :total="pagination.total">
      </el-pagination>
    </div>
    
    <!-- 添加/编辑课程对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" :close-on-click-modal="false">
      <el-form :model="courseForm" :rules="courseRules" ref="courseForm" label-width="100px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName"></el-input>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseType">
          <el-select v-model="courseForm.courseType" placeholder="请选择课程类型">
            <el-option
              v-for="item in courseTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授课教师" prop="teacherName">
          <el-input v-model="courseForm.teacherName"></el-input>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input v-model.number="courseForm.credit" type="number" placeholder="请输入学分"></el-input>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input type="textarea" v-model="courseForm.description" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="courseForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="已开课"
            inactive-text="未开课">
          </el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 添加自定义验证规则确保学分是数字
    const validateCredit = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        return callback(new Error('请输入学分'));
      }
      if (isNaN(value)) {
        return callback(new Error('学分必须是数字'));
      }
      if (value < 1 || value > 10) {
        return callback(new Error('学分必须在1到10之间'));
      }
      callback();
    };
    
    return {
      mockData: [], // 存储完整数据
      courseData: [], // 存储当前页数据
      loading: false,
      dialogVisible: false,
      dialogTitle: '添加课程',
      isEdit: false,
      courseTypes: [
        { value: 1, label: '必修课' },
        { value: 2, label: '选修课' },
        { value: 3, label: '公共课' },
        { value: 4, label: '专业课' }
      ],
      searchParams: {
        courseName: '',
        courseType: ''
      },
      pagination: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      courseForm: {
        id: '',
        courseName: '',
        courseType: '',
        teacherName: '',
        credit: 2,
        description: '',
        status: 0
      },
      courseRules: {
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        courseType: [
          { required: true, message: '请选择课程类型', trigger: 'change' }
        ],
        teacherName: [
          { required: true, message: '请输入授课教师', trigger: 'blur' }
        ],
        credit: [
          { required: true, validator: validateCredit, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    formatCourseType(type) {
      const found = this.courseTypes.find(item => item.value === type);
      return found ? found.label : '未知类型';
    },
    async getCourseList() {
      this.loading = true;
      try {
        // 模拟API请求延迟
        await new Promise(resolve => setTimeout(resolve, 500));
        
        // 过滤数据
        let filteredData = this.mockData;
        if (this.searchParams.courseName) {
          filteredData = filteredData.filter(item => 
            item.courseName.includes(this.searchParams.courseName)
          );
        }
        if (this.searchParams.courseType) {
          filteredData = filteredData.filter(item => 
            item.courseType === this.searchParams.courseType
          );
        }
        
        // 更新总数
        this.pagination.total = filteredData.length;
        
        // 分页处理
        const start = (this.pagination.page - 1) * this.pagination.pageSize;
        const end = start + this.pagination.pageSize;
        this.courseData = filteredData.slice(start, end);
        
      } catch (error) {
        console.error('获取课程列表失败:', error);
        this.$message.error('获取课程列表失败');
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.pagination.page = 1;
      this.getCourseList();
    },
    resetSearch() {
      this.searchParams = {
        courseName: '',
        courseType: ''
      };
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.getCourseList();
    },
    handleAddCourse() {
      this.dialogTitle = '添加课程';
      this.isEdit = false;
      this.resetForm();
      this.dialogVisible = true;
    },
    editCourse(row) {
      this.dialogTitle = '编辑课程';
      this.isEdit = true;
      this.courseForm = { ...row };
      this.dialogVisible = true;
    },
    deleteCourse(id) {
      this.$confirm('确定要删除此课程吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除数据
        this.mockData = this.mockData.filter(item => item.id !== id);
        this.pagination.total = this.mockData.length;
        this.getCourseList();
        this.$message.success('删除成功');
      }).catch(() => {
        // User canceled
      });
    },
    resetForm() {
      this.courseForm = {
        id: '',
        courseName: '',
        courseType: '',
        teacherName: '',
        credit: 2,
        description: '',
        status: 0
      };
      this.$nextTick(() => {
        if (this.$refs.courseForm) {
          this.$refs.courseForm.clearValidate();
        }
      });
    },
    submitForm() {
      this.$refs.courseForm.validate(valid => {
        if (valid) {
          this.courseForm.credit = Number(this.courseForm.credit);
          
          if (this.isEdit) {
            // 更新数据
            const index = this.mockData.findIndex(item => item.id === this.courseForm.id);
            if (index !== -1) {
              this.mockData.splice(index, 1, { ...this.courseForm });
            }
            this.$message.success('修改成功');
          } else {
            // 添加数据
            const newId = this.mockData.length > 0 
              ? Math.max(...this.mockData.map(item => item.id)) + 1 
              : 1;
            this.mockData.push({
              ...this.courseForm,
              id: newId,
              studentCount: 0
            });
            this.$message.success('添加成功');
          }
          
          // 重置到第一页并刷新列表
          this.pagination.page = 1;
          this.dialogVisible = false;
          this.getCourseList();
        }
      });
    }
  },
  created() {
    // 初始化mock数据
    this.mockData = [
    {
      id: 1,
      courseName: '大学英语（一）',
      courseType: 3,
      teacherName: '李华',
      studentCount: 120,
      credit: 3,
      status: 2,
      description: '大学英语基础课程'
    },
    {
      id: 2,
      courseName: '高等数学（上）',
      courseType: 3,
      teacherName: '王强',
      studentCount: 150,
      credit: 4,
      status: 2,
      description: '高等数学上册课程'
    },
    {
      id: 3,
      courseName: '数据结构',
      courseType: 4,
      teacherName: '张敏',
      studentCount: 80,
      credit: 4,
      status: 1,
      description: '数据结构与算法课程'
    },
    {
      id: 4,
      courseName: '市场营销学',
      courseType: 2,
      teacherName: '赵刚',
      studentCount: 60,
      credit: 2,
      status: 0,
      description: '市场营销基础课程'
    },
    {
      id: 5,
      courseName: '中国近现代史纲要',
      courseType: 3,
      teacherName: '陈丽',
      studentCount: 100,
      credit: 2,
      status: 2,
      description: '中国近现代历史课程'
    },
    {
      id: 6,
      courseName: '计算机网络基础',
      courseType: 4,
      teacherName: '周勇',
      studentCount: 70,
      credit: 3,
      status: 1,
      description: '计算机网络基础课程'
    },
    {
      id: 7,
      courseName: '管理学原理',
      courseType: 2,
      teacherName: '吴芳',
      studentCount: 50,
      credit: 2,
      status: 0,
      description: '管理学基础课程'
    },
    {
      id: 8,
      courseName: '大学物理（下）',
      courseType: 3,
      teacherName: '郑伟',
      studentCount: 130,
      credit: 3,
      status: 2,
      description: '大学物理下册课程'
    },
    {
      id: 9,
      courseName: '西方经济学（微观）',
      courseType: 4,
      teacherName: '刘娜',
      studentCount: 90,
      credit: 3,
      status: 1,
      description: '西方微观经济学课程'
    },
    {
      id: 10,
      courseName: '素描基础',
      courseType: 2,
      teacherName: '孙阳',
      studentCount: 40,
      credit: 2,
      status: 0,
      description: '基础素描技巧课程'
    },
    {
      id: 11,
      courseName: '人体解剖学',
      courseType: 4,
      teacherName: '郭军',
      studentCount: 65,
      credit: 4,
      status: 2,
      description: '人体结构解剖学课程'
    },
    {
      id: 12,
      courseName: '国际法',
      courseType: 4,
      teacherName: '黄玲',
      studentCount: 55,
      credit: 3,
      status: 1,
      description: '国际法基础课程'
    },
    {
      id: 13,
      courseName: '机械制图',
      courseType: 4,
      teacherName: '许峰',
      studentCount: 75,
      credit: 3,
      status: 0,
      description: '机械制图基础课程'
    },
    {
      id: 14,
      courseName: '古代汉语',
      courseType: 4,
      teacherName: '江雪',
      studentCount: 85,
      credit: 3,
      status: 2,
      description: '古代汉语文学课程'
    },
    {
      id: 15,
      courseName: '幼儿教育心理学',
      courseType: 4,
      teacherName: '吕梅',
      studentCount: 60,
      credit: 2,
      status: 1,
      description: '幼儿心理发展课程'
    },
    {
      id: 16,
      courseName: '财务会计',
      courseType: 4,
      teacherName: '唐毅',
      studentCount: 70,
      credit: 3,
      status: 0,
      description: '财务会计基础课程'
    }
  ];
    // 获取分页数据
    this.getCourseList();
  }
};
</script>

<style lang="scss" scoped>
.header {
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.table {
  margin-top: 10px;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 5px 12px 0 rgba(0, 0, 0, 0.1);
}
.page {
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>